package gorilla

import (
	"fmt"
	"net/http"
	"strconv"
	"strings"

	ws "github.com/gorilla/websocket"
)

/**
gorilla websocket  使用upgrader升级，转为gorilla connection
*/
func GorillaServer() {
	http.HandleFunc("/hello", func(writer http.ResponseWriter, request *http.Request) {
		writer.Write([]byte("hello"))
		writer.WriteHeader(200)
	})

	fs := http.FileServer(http.Dir("/Users/fanshuai/project-test/go/demo/web/websocket/static"))
	http.Handle("/static/", http.StripPrefix("/static/", fs))

	http.HandleFunc("/push", websocket)

	http.ListenAndServe(":9000", nil)
}

var upgrader = ws.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
	CheckOrigin: func(r *http.Request) bool {
		upgrade := r.Header["Upgrade"]
		if (len(upgrade) == 0 || strings.ToLower(upgrade[0]) != "websocket") {
			return false
		}
		return true
	},
}

func websocket(writer http.ResponseWriter, request *http.Request) {
	if ws.IsWebSocketUpgrade(request) {
		conn, err := upgrader.Upgrade(writer, request, writer.Header())
		if err != nil {
			fmt.Println(err)
		}

		for {
			for i := 0; i < 5; i++ {
				conn.WriteMessage(ws.TextMessage, []byte("hello"))
			}

			messageType, data, err := conn.ReadMessage()
			fmt.Println("messageType=" + strconv.Itoa(messageType))
			if err != nil {
				fmt.Println(err)
				break
			}

			fmt.Println("from client:" + string(data))
		}
	} else {
		writer.Write([]byte("error"))
		writer.WriteHeader(400)
	}
}
